import { Exclude } from 'class-transformer';
import { IsPhoneNumber } from 'class-validator';
import {
  BeforeInsert,
  BeforeUpdate,
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import * as bcrypt from 'bcrypt';

@Entity('admin_account', { schema: 'shop' })
export class Account {
  constructor(partial: Partial<Account>) {
    Object.assign(this, partial);
  }

  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar', { name: 'account_name', length: 50 })
  username: string;

  @Column('varchar', { select: false })
  @Exclude()
  password: string;

  @Column('varchar', { name: 'phone_number' })
  @IsPhoneNumber('CH', { message: '请输入正确的手机号' })
  phoneNumber: string;

  @Column('tinyint', {
    name: 'is_delete',
    default: 1,
    select: false,
    comment: '逻辑删除标识, 1: 存在, -1: 删除',
  })
  @Exclude()
  isDelete: number;

  @Column('varchar', {
    name: 'role',
    length: 10,
    default: 'user',
    comment: '用户角色; 默认是 user, 只存在一个 admin 角色的账号',
  })
  role: string;

  @CreateDateColumn({ name: 'create_time', comment: '账号创建时间' })
  createTime: Date;

  @UpdateDateColumn({ name: 'modify_time', comment: '修改时间' })
  modifyTime: Date;

  @BeforeInsert()
  async encryptPassword() {
    this.password = bcrypt.hashSync(this.password, 10);
  }

  @BeforeUpdate()
  async updatePassword() {
    this.password = bcrypt.hashSync(this.password, 10);
  }

  // 限制只有一个 admin 角色的账号
  @BeforeInsert()
  async addRole() {
    if (this.username === 'root') {
      this.role = 'admin';
    }
  }
}
